package com.leonwoodstudio.eventdetectionclient;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;

import com.leonwoodstudio.eventdetectionclient.eventmessage.ParsedEventMessageToSave;
import com.leonwoodstudio.eventdetectionclient.utils.DatabaseHelper;

/**
 * Created by win7 on 2017/4/9.
 */
public class EventHistoryLoadFromDbAsyncTask extends AsyncTask<Void, Void, Void> {
    EventHistoryFragment fragment;

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SQLiteDatabase database = MainActivity.event_history_database;
        Cursor cursor = database.query(DatabaseHelper.EVENT_HISTORY_TABLE_NAME,
                new String[]{"_id", "url", "pic_name", "date", "camera_idx", "lane_inx", "event_type", "coordinate_x", "coordinate_y"},
                null, null, null, null, null);
        while(cursor.moveToNext()) {
            ParsedEventMessageToSave parsed = new ParsedEventMessageToSave();
            parsed.setUrl(cursor.getString(cursor.getColumnIndex("url")));
            parsed.setPic_name(cursor.getString(cursor.getColumnIndex("pic_name")));
            parsed.setDate(cursor.getString(cursor.getColumnIndex("date")));
            parsed.setCamera_idx(cursor.getString(cursor.getColumnIndex("camera_idx")));
            parsed.setLane_inx(cursor.getString(cursor.getColumnIndex("lane_inx")));
            parsed.setEvent_type(cursor.getString(cursor.getColumnIndex("event_type")));
            parsed.setCoordinate_x(cursor.getString(cursor.getColumnIndex("coordinate_x")));
            parsed.setCoordinate_y(cursor.getString(cursor.getColumnIndex("coordinate_y")));
            fragment.event_history_list_view_adapter.event_history_list.add(0, parsed);
        }
        return null;
    }

    public EventHistoryLoadFromDbAsyncTask(Fragment fragment) {
        this.fragment = (EventHistoryFragment)fragment;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        fragment.event_history_list_view_adapter.notifyDataSetChanged();
    }
}
